package net.caixiaomi.info.app;

import android.annotation.SuppressLint;
import android.content.Context;

import net.caixiaomi.info.util.Constants;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;

public class CrashHandler implements UncaughtExceptionHandler {
    private Context mContext;
    private UncaughtExceptionHandler mDefaultHandler;

    public CrashHandler(Context context) {
        mContext = context;
    }

    /**
     * Init
     */
    public void init() {

        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 处理异常，如果处理失败，则调用系统默认异常处理方式
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        // 保存crash日志
//        saveCrashInfo2File(ex);
        if (Constants.DEBUG) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 保存crash信息到文件
     *
     * @param ex
     */
    @SuppressLint("SimpleDateFormat")
    public boolean saveCrashInfo2File(Throwable ex) {

        try {

            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            String log = sw.toString();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
